// Package _1_TwoSum
// Date        : 2022/12/5 14:29
// Version     : 1.0.0
// Author      : 代码小学生王木木
// Email       : 18574945291@163.com
// Description : https://leetcode.cn/problems/two-sum/?favorite=2cktkvj
package main

import (
	"fmt"
	"sort"
)

/*
nums = [2,7,11,15], target = 9
[0,1]
*/

func twoSum1(nums []int, target int) []int {
	if len(nums) < 2 {
		return nil
	}
	ans := make([]int, 2)
	// 保存值和下标
	hashMap := make(map[int]int)
	// 1. 遍历数组，将数组的元素和下标保存起来
	for k, v := range nums {
		hashMap[v] = k
	}
	for i, val := range nums {
		if v, ok := hashMap[target-val]; ok && v != i {
			ans[0] = i
			ans[1] = v
			return ans
		}
	}
	return ans
}

// 使用排序 + 双指针
func twoSum(nums []int, target int) []int {
	if len(nums) < 2 {
		return nil
	}
	var ans []int
	sort.Ints(nums)
	i, j := 0, len(nums)-1
	for i < j {
		if nums[i]+nums[j] > target {
			j--
		} else if nums[i]+nums[j] < target {
			i++
		} else if nums[i]+nums[j] == target && i != j {
			ans = append(ans, i)
			ans = append(ans, j)
			return ans
		}
	}
	return ans
}

func main() {
	fmt.Println(twoSum([]int{3, 3}, 6))
}
